<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/hexo/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/hexo/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/hexo/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/hexo/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/hexo/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/hexo/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/hexo/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Tony's hexo blog by Next">










<meta name="description" content="又好久不写东西了，最近在开发一个新项目的时候，需要用到发号器，之前有CV过一个雪花算法（snowflakes）的实现方法，但那个比较传统，也有一个大多数雪花算法的通病，就是生成的id过长，传到前端的时候需要转成字符串，不然js解析会失准。说到这，简单说一下为什么要用雪花算法来做发号器，当然网上也有各种看法，我就简单说说自己的看法。在关系型数据库的表结构里，主键的作用是非常重要的，其重要性不光体现在">
<meta property="og:type" content="article">
<meta property="og:title" content="分享一个小清新的雪花算法和应用实例">
<meta property="og:url" content="https://tony_df.coding.net/2021/04/09/分享一个小清新的雪花算法和应用实例/index.html">
<meta property="og:site_name" content="Tony&#39;s blog">
<meta property="og:description" content="又好久不写东西了，最近在开发一个新项目的时候，需要用到发号器，之前有CV过一个雪花算法（snowflakes）的实现方法，但那个比较传统，也有一个大多数雪花算法的通病，就是生成的id过长，传到前端的时候需要转成字符串，不然js解析会失准。说到这，简单说一下为什么要用雪花算法来做发号器，当然网上也有各种看法，我就简单说说自己的看法。在关系型数据库的表结构里，主键的作用是非常重要的，其重要性不光体现在">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://tony_df.coding.net/2021/04/09/分享一个小清新的雪花算法和应用实例/1.png">
<meta property="og:image" content="https://tony_df.coding.net/2021/04/09/分享一个小清新的雪花算法和应用实例/2.png">
<meta property="og:updated_time" content="2021-04-09T00:46:10.558Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="分享一个小清新的雪花算法和应用实例">
<meta name="twitter:description" content="又好久不写东西了，最近在开发一个新项目的时候，需要用到发号器，之前有CV过一个雪花算法（snowflakes）的实现方法，但那个比较传统，也有一个大多数雪花算法的通病，就是生成的id过长，传到前端的时候需要转成字符串，不然js解析会失准。说到这，简单说一下为什么要用雪花算法来做发号器，当然网上也有各种看法，我就简单说说自己的看法。在关系型数据库的表结构里，主键的作用是非常重要的，其重要性不光体现在">
<meta name="twitter:image" content="https://tony_df.coding.net/2021/04/09/分享一个小清新的雪花算法和应用实例/1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/hexo/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Tony'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://tony_df.coding.net/2021/04/09/分享一个小清新的雪花算法和应用实例/">





  <title>分享一个小清新的雪花算法和应用实例 | Tony's blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/hexo/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学着码代码,学着码人生;</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/hexo/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/hexo/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/hexo/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://tony_df.coding.net/hexo/2021/04/09/分享一个小清新的雪花算法和应用实例/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/hexo/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">分享一个小清新的雪花算法和应用实例</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2021-04-09T08:33:56+08:00">
                2021-04-09
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>又好久不写东西了，最近在开发一个新项目的时候，需要用到发号器，之前有CV过一个雪花算法（snowflakes）的实现方法，但那个比较传统，也有一个大多数雪花算法的通病，就是生成的id过长，传到前端的时候需要转成字符串，不然js解析会失准。<br>说到这，简单说一下为什么要用雪花算法来做发号器，当然网上也有各种看法，我就简单说说自己的看法。<br>在关系型数据库的表结构里，主键的作用是非常重要的，其重要性不光体现在标识唯一，还有索引和占用空间等方面，在以前的项目里，我一般选择uuid（guid）或者自增种子来用作主键，这两种主键的方式都有各自的优缺点。比如uuid最大的优点就是不依赖任何外部方式，仅凭数据库本身或者代码自带的能力就可以生成，而且近乎绝对的唯一，缺点就是，uuid本身没有任何业务型，当我们检索数据的时候，不得不依赖主键之外的其他字段作为排序字段，而且uuid占用的字符空间较大，当数据量到一定规模后，这是非常损耗性能的操作，而且，也不利于后期的分库分表等操作，但uuid也有非常适合的使用场景，比如做某些请求日志相关模型的主键。<br>而自增id则会丧失一部分的灵活性，当我们需要手动获得主键值执行插入操作的时候，操作会比较麻烦，不像uuid那样可以提前生成。而且在高并发场景下，自增id的生成，容易发生冲突，造成业务执行失败。<br>因此，我们需要一种既能保证唯一，支持高并发，且具有业务性特点的字段值作为主键，雪花算法便具备以上特点，而且，使用雪花算法还有一个很大的好处是，它的生成是有规律的，我们可以直接逆向解析用雪花算法生成的值，得到对应的机器码，时间戳等内容。<br>更多的我就不介绍了，看一下这个新的雪花算法把，开源地址如下<a href="https://gitee.com/yitter/idgenerator" target="_blank" rel="noopener">https://gitee.com/yitter/idgenerator</a>，文档的介绍也非常完整，不再多说，直接来看下应用场景吧。我这里是在.net(core) 5.0框架下进行引用</p>
<p>首先根据文档，在项目中引入Yitter.IdGenerator，可直接通过cli命令（packages install Yitter.IdGenerator）或者在nuget包里直接搜索下载；<br><img src="1.png" alt="1"><br>然后新建一个接口文件，定义好需要的抽象函数</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title">IYitIdHelper</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="keyword">long</span> <span class="title">NextId</span>(<span class="params"></span>)</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">SetIdGenerator</span>(<span class="params">IdGeneratorOptions options</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>接下来引入helper操作类或者自己创对应的类，并调用算法</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">public class YitIdHelper: Interfaces.IYitIdHelper</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> IIdGenerator _IdGenInstance = <span class="literal">null</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> IIdGenerator IdGenInstance =&gt; _IdGenInstance;</span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;summary&gt;</span></span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> 设置参数，建议程序初始化时执行一次</span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;/summary&gt;</span></span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;param name="options"&gt;</span><span class="doctag">&lt;/param&gt;</span></span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">SetIdGenerator</span>(<span class="params">IdGeneratorOptions options</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        _IdGenInstance = <span class="keyword">new</span> DefaultIdGenerator(options);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;summary&gt;</span></span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> 生成新的Id</span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> 调用本方法前，请确保调用了 SetIdGenerator 方法做初始化。</span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> 否则将会初始化一个WorkerId为1的对象。</span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;/summary&gt;</span></span></span><br><span class="line">    <span class="comment"><span class="doctag">///</span> <span class="doctag">&lt;returns&gt;</span><span class="doctag">&lt;/returns&gt;</span></span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">NextId</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">if</span> (_IdGenInstance == <span class="literal">null</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            _IdGenInstance = <span class="keyword">new</span> DefaultIdGenerator(</span><br><span class="line">                <span class="keyword">new</span> IdGeneratorOptions() &#123; WorkerId = <span class="number">1</span> &#125;</span><br><span class="line">                );</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> _IdGenInstance.NewLong();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后，我们在startup文件的ConfigureServices函数里，注入服务，根据文档的介绍，把服务的生命周期注入成单例模式</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">ConfigureServices</span>(<span class="params">IServiceCollection services</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">//其他服务</span></span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">    services.AddSingleton&lt;IYitIdHelper, YitIdHelper&gt;();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后就可以在需要的地方进行调用了生成了</p>
<figure class="highlight c#"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">public class UserAdminTeamRespo :RespositoryBase&lt;User_AdminTeam&gt;,Interfaces.IUserAdminTeamRespo</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">private</span> IYitIdHelper yitId;</span><br><span class="line">    <span class="comment">//构造函数注入IYitId服务</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">UserAdminTeamRespo</span>(<span class="params">IFreeSql fsql, IYitIdHelper yitId</span>) : <span class="title">base</span>(<span class="params">fsql</span>)</span></span><br><span class="line"><span class="function"></span>    &#123;</span><br><span class="line">        <span class="keyword">this</span>.yitId = yitId;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//定义你自己的实现方法</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">yourMethod</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> model = <span class="keyword">new</span> YourModel()&#123;</span><br><span class="line">            id=yitId.NextId(),</span><br><span class="line">            <span class="comment">//其他字段</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//其他业务代码</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如此便完成了集成的工作，看下生成的效果。<br><img src="2.png" alt="2"><br>小而美，小清新。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/hexo/2021/01/21/IdentityServer4-采坑实例/" rel="next" title="IdentityServer4 采坑实例">
                <i class="fa fa-chevron-left"></i> IdentityServer4 采坑实例
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/hexo/2021/04/14/聊聊有关集成在线支付那点事儿/" rel="prev" title="聊聊有关集成在线支付那点事儿">
                聊聊有关集成在线支付那点事儿 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5bbb2338b87602f0" async="async"></script>
</div>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zOTA1My8xNTU4MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Tony</p>
              <p class="site-description motion-element" itemprop="description">学习总结</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/hexo/archives/">
              
                  <span class="site-state-item-count">58</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/hexo/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/hexo/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hexo/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/hexo/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/hexo/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/hexo/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/hexo/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/hexo/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

</body>
</html>
